package com.seawater.http;

import feign.RequestInterceptor;
import feign.RequestTemplate;

public class AuthorizationRequestInterceptor implements RequestInterceptor {
    private static final String ENCRYPT_METHOD = "HmacSHA256";
    private static final String METHOD_POST = "POST";
    private final String appId;
    private final String appSecret;

    public AuthorizationRequestInterceptor(String appId, String appSecret) {
        this.appId = appId;
        this.appSecret = appSecret;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String body = null;
        if (requestTemplate.method().equalsIgnoreCase(METHOD_POST)) {
            body = requestTemplate.requestBody().asString();
        }
        String signature = HmacSHAUtil.sign(appId, appSecret,body);
        String authorization = new StringBuilder(ENCRYPT_METHOD)
                .append(" ")
                .append("appId=")
                .append(appId)
                .append(",")
                .append(" ")
                .append("signature=")
                .append(signature).toString();
        requestTemplate.header("Authorization", authorization);
    }
}
